package com.ctg.polling.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ctg.polling.domain.EmployeeStatus;
import com.ctg.polling.domain.JPollingUser;
import com.ctg.polling.domain.UserRole;
import com.ctg.polling.web.dataobject.CreateUserDO;

@RequestMapping("/create_user")
@Controller
public class CreateUserController {

	Logger logger = Logger.getLogger(CreateUserController.class);

	/*
    @RequestMapping(method=RequestMethod.POST)
    public String create_user(HttpServletRequest request, Model uiModel) {
    	// fetch attributes.
    	String username = request.getParameter("username");
    	String password = request.getParameter("password");
    	String email = request.getParameter("email");
    	
    	// validate attributes.
    	if (username == null) {
    		
    	}
    	
    	return "index";
    }*/
    
	/**
	 * Prepare user create form parameters.
	 * @param request
	 * @param uiModel
	 * @return displayed page.
	 */
    @RequestMapping(method=RequestMethod.GET)
    public String create(Model uiModel) {
    	
    	CreateUserDO pollingUser = new CreateUserDO();
    	uiModel.addAttribute("JPollingUser", pollingUser);
    	return "create_user/create";
    }
    
    /**
     * Fetch user create parameters.
     * @param request
     * @param uiModel
     * @return
     */
    @RequestMapping(method=RequestMethod.POST)
    public String create_user(@Valid CreateUserDO pollingUser, BindingResult bindingResult, Model uiModel, HttpServletRequest request) {
    	if (bindingResult.hasErrors()) {
            uiModel.addAttribute("JPollingUser", pollingUser);
            return "create_user/create";
        }
    	
    	JPollingUser pollingUser2 = new JPollingUser();
    	pollingUser2.setEmail(pollingUser.getEmail());
    	pollingUser2.setUsername(pollingUser.getUsername());
    	pollingUser2.setPassword(pollingUser.getPassword());
    	pollingUser2.setStatus(EmployeeStatus.ACTIVE);
    	pollingUser2.setUserRole(UserRole.ROLE_USER);
    	pollingUser2.persist();
    	
    	return "redirect:/login";
    }
}